package base;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

public class Server {
	public ServerSocket request;
	public int port;
	
	public Server(int port) {
		this.port = port;
	}
	
	public void init(){
		try{
			this.request = new ServerSocket(port);
		}catch(Exception e){
			System.out.println("Server constructor.");
		}
	}
	
	public Map<String,String> analyzeFromClient(Socket socket) throws IOException,JSONException {
		Map<String,String> message = new HashMap<String,String>();
		DataInputStream from = null;
		String strInput = "";
		Iterator keys  = null;
		from = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] by = new byte[2048];  
        int n;
        while((n=from.read(by))!=-1){  
            baos.write(by,0,n);           
        } 
        strInput = new String(baos.toByteArray());  
        
        JSONObject json = new JSONObject(strInput);
        //
        //System.out.println(json.keys().next().toString());
        keys = json.keys();
        while(keys.hasNext()){
        	String key = keys.next().toString();
        	String value = json.getString(key);
        	message.put(key, value);
        }
        System.out.println(message);
		return message;
	}
	
	public void sendToClient(Socket socket,Map<String,String> message) throws IOException{
		DataOutputStream outputStream;
		JSONObject json = null;
		json = new JSONObject(message);  
        String jsonString = json.toString();                        
        //outputStream = new DataOutputStream(new BufferedOutputStream (socket.getOutputStream()));
        outputStream = new DataOutputStream(socket.getOutputStream());
        //System.out.println(jsonString);
        outputStream.writeUTF(jsonString);
        System.out.println("ttt");
	}
	
	public void pushToClient(List<Socket> sockets,Map<String,String> message) throws IOException{
		DataOutputStream outputStream;
		JSONObject json = null;
		json = new JSONObject(message);  
        String jsonString = json.toString();                        
        //outputStream = new DataOutputStream(new BufferedOutputStream (socket.getOutputStream()));
        for (Socket socket:sockets){
        	outputStream = new DataOutputStream(socket.getOutputStream());
            //System.out.println(jsonString);
            outputStream.writeUTF(jsonString);
        }
        System.out.println("ttt");
	}
}
